Imports System.IO
Imports System.Text

Public Class frmFileList

    Private db As Database = Database.db
    Private files As String()

    Private Sub refreshFileList()
        files = db.getFileList()
        lstFilesAvailable.Items.Clear()
        If files.Length > 1 Then
            For i As Integer = 1 To files.Length - 1
                lstFilesAvailable.Items.Add(files(i))
            Next
            lstFilesAvailable.Enabled = True
            lstFilesAvailable.SelectedIndex = 0
            If db.getMyPrivateKey Is Nothing Then
                frmPrivateKey.Show()
                frmPrivateKey.BringToFront()
            End If
        Else
            lstFilesAvailable.Items.Add("                   -- NO FILES AVAILABLE --")
            lstFilesAvailable.Enabled = False
        End If
    End Sub

    Private Sub frmFileList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        refreshFileList()
    End Sub

    Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
        If db.getMyPrivateKey Is Nothing Then
            frmPrivateKey.Show()
            frmPrivateKey.BringToFront()
            frmPrivateKey.Focus()
        Else
            Dim selectedFileName As String
            selectedFileName = lstFilesAvailable.SelectedItem

            SaveFileDialog1.OverwritePrompt = True
            SaveFileDialog1.FileName = selectedFileName
            SaveFileDialog1.ShowDialog()
            Me.Enabled = False
            If db.downloadFile(selectedFileName, SaveFileDialog1.FileName) Then
                MsgBox("file downloaded properly")
            Else
                MsgBox("file download failed")
            End If
            Me.Enabled = True
        End If
        refreshFileList()
        Form1.Show()
        Form1.BringToFront()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        refreshFileList()
    End Sub
End Class